﻿create procedure [dbo].[usp_AppDomainInsert]
	@BaseDirectory nvarchar(1024)
	, @DomainManager nvarchar(256)
	, @FriendlyName nvarchar(256)
	, @Id int
	, @RelativeSearchPath nvarchar(1024)
as

begin try
	
	begin transaction
	
		if not exists(select * from [dbo].[AppDomain] where ([BaseDirectory] = @BaseDirectory or ([BaseDirectory] is null and @BaseDirectory is null)) and
			                                                ([DomainManager] = @DomainManager or ([DomainManager] is null and @DomainManager is null)) and 
				                                            ([FriendlyName] = @FriendlyName or ([FriendlyName] is null and @FriendlyName is null)) and
					                                        ([Id] = @Id or ([Id] is null and @Id is null)) and
					                                        ([RelativeSearchPath] = @RelativeSearchPath or ([RelativeSearchPath] is null and @RelativeSearchPath is null)))
		
			begin
										                              
				insert [dbo].[AppDomain]
				(
					[BaseDirectory]
					, [DomainManager]
					, [FriendlyName]
					, [Id]
				)
				values
				(
					@BaseDirectory
					, @DomainManager
					, @FriendlyName
					, @Id
				)
				
				select [AppDomainId], [ConcurrencyId], [Created], [Updated] from [dbo].[AppDomain] where @@rowcount > 0 and [AppDomainId] = scope_identity()
			
			end
			
		else
			
			begin
			
				select [AppDomainId], [ConcurrencyId], [Created], [Updated] from [dbo].[AppDomain] where ([BaseDirectory] = @BaseDirectory or ([BaseDirectory] is null and @BaseDirectory is null)) and
																  		                         ([DomainManager] = @DomainManager or ([DomainManager] is null and @DomainManager is null)) and
																		                         ([FriendlyName] = @FriendlyName or ([FriendlyName] is null and @FriendlyName is null)) and
																		                         ([Id] = @Id or ([Id] is null and @Id is null)) and
																		                         ([RelativeSearchPath] = @RelativeSearchPath or ([RelativeSearchPath] is null and @RelativeSearchPath is null)) 
			end
	
	commit transaction

end try
	
begin catch
	if @@trancount > 0
	begin
		rollback transaction;
	end
	execute [dbo].[usp_SqlErrorInsert]
end catch


